<?php

namespace Base\Lib\Sms;

class Eucp extends \Windward\Core\Base
{

    protected $host = 'http://sdk4report.eucp.b2m.cn:8080/';
    protected $cdkey = '';
    protected $password = '';

    public function __construct(\Windward\Core\Container $container, $cdkey = '', $password = '')
    {
        $this->container = $container;
        $this->cdkey = $cdkey;
        $this->password = $password;
    }

    public function buildQuery($data = [])
    {
        $data = ['cdkey' => $this->cdkey, 'password' => $this->password] + $data;
        return http_build_query($data);
    }

    public function xmlToArray($xml = '')
    {
        if (!$xml) {
            return [];
        }
        $xml = trim($xml);
        return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    }

    public function request($uri = '')
    {
        $response = trim(file_get_contents($uri));
        $this->logger->log('sms', "[{$uri}],[{$response}]");
        return $this->xmlToArray($response);
    }

    /**
     * 激活
     * @return boolean
     */
    public function regist()
    {
        $uri = $this->host . 'sdkproxy/regist.action';
        $response = $this->request($uri . '?' . $this->buildQuery());
        return $response['error'] === '0';
    }

    /**
     * 发送短信
     * @param mix $phone
     * @param string $msg
     * @return boolean
     */
    public function send($phone, $msg = '')
    {
        if (!$phone || !$msg) {
            return false;
        }
        $uri = $this->host . 'sdkproxy/sendsms.action';
        $data = ['message' => $msg];
        if (is_array($phone)) {
            $data['phone'] = implode(',', $phone);
        } elseif (is_string($phone)) {
            $data['phone'] = $phone;
        } else {
            return false;
        }
        $response = $this->request($uri . '?' . $this->buildQuery($data));
        return $response['error'] === '0';
    }

    /**
     * 查询余额
     * @return mix
     */
    public function query()
    {
        $uri = $this->host . 'sdkproxy/querybalance.action';
        $response = $this->request($uri . '?' . $this->buildQuery());
        if ($response['error'] === '0') {
            return $response['message'];
        }
        return '';
    }

}
